package com.ruoyi.web.controller.system;

import java.time.*;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.Pq;
import com.ruoyi.system.domain.Qdkb;
import com.ruoyi.system.domain.Yg;
import com.ruoyi.system.domain.bo.CountNumBo;
import com.ruoyi.system.domain.bo.WdqdBo;
import com.ruoyi.system.domain.vo.WdqdVo;
import com.ruoyi.system.domain.vo.YgVo;
import com.ruoyi.system.service.IQdkbService;
import com.ruoyi.system.service.IYgService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Wdqd;
import com.ruoyi.system.service.IWdqdService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 我的抢单/我的职位Controller
 *
 * @author ruoyi
 * @date 2025-04-09
 */
@RestController
@RequestMapping("/system/wdqd")
public class WdqdController extends BaseController
{
    @Autowired
    private IWdqdService wdqdService;
    @Autowired
    private IQdkbService qdkbService;
    @Autowired
    private IYgService ygService;

    /**
     * 查询我的抢单/我的职位列表
     */
    @PreAuthorize("@ss.hasPermi('system:wdqd:list')")
    @GetMapping("/list")
    public TableDataInfo list(WdqdVo wdqdVo)
    {


        SysUser sysUser = getLoginUser().getUser();
        boolean contains3OR4 = sysUser.getRoles().stream().anyMatch(v->v.getRoleId()==3L || v.getRoleId()==4L);

        boolean contains6 = sysUser.getRoles().stream().anyMatch(v->v.getRoleId()==6L);

        boolean contains1OR2=true;
        if(sysUser.getRoles()!=null && sysUser.getRoles().size()!=0){
            contains1OR2 = sysUser.getRoles().stream().anyMatch(v->v.getRoleId()==1L || v.getRoleId()==2L);
        }

        if(contains3OR4){
            wdqdVo.setUserId(getUserId());
        }else if(contains6){
            wdqdVo.setEnterUserId(getUserId());
        }else if(!contains1OR2){
            return getDataTable(new ArrayList<>());
        }
        List<WdqdBo> list=null;
        if(wdqdVo.getStatus()!=null && !wdqdVo.getStatus().equals("")){
            LocalDate today = LocalDate.now();
            wdqdVo.setNewTime(today.toString());
            startPage();
            list = wdqdService.selectWdqdList(wdqdVo);
        }else {
            startPage();
            list = wdqdService.selectWdqdListOne(wdqdVo);
        }
        Long [] qdkbIds=list.stream().map(v->v.getQdkbId()).toArray(Long[]::new);
        Map<String,Integer> numList=new HashMap<>();
        if(qdkbIds!=null && qdkbIds.length>0){
            List<CountNumBo> countNumBos = ygService.selectcountNums(qdkbIds);
            if(countNumBos!=null && countNumBos.size()!=0){
                for (CountNumBo c: countNumBos) {
                    numList.put(c.getQdkbId()+"_"+c.getStatusTwo(),c.getNum());
                }
            }
        }
        for (WdqdBo w: list) {
            w.setAboutFaceNum(numList.get(w.getQdkbId()+"_2"));
            w.setToFaceNum(numList.get(w.getQdkbId()+"_3"));
            w.setOfferNum(numList.get(w.getQdkbId()+"_4"));
            w.setEntryNum(numList.get(w.getQdkbId()+"_6"));
        }


        return getDataTable(list);
    }



    @PreAuthorize("@ss.hasPermi('system:wdqd:listzw')")
    @GetMapping("/listzw")
    public TableDataInfo listzw(WdqdVo wdqdVo)
    {
        wdqdVo.setUserId(getUserId());
        LocalDate today = LocalDate.now();
        wdqdVo.setNewTime(today.toString());
        startPage();
        List<WdqdBo>list = wdqdService.selectWdqdzwList(wdqdVo);
        Long [] qdkbIds=list.stream().map(v->v.getQdkbId()).toArray(Long[]::new);
        Map<String,Integer> numList=new HashMap<>();
        if(qdkbIds!=null && qdkbIds.length>0){
            List<CountNumBo> countNumBos = ygService.selectcountNums(qdkbIds);
            if(countNumBos!=null && countNumBos.size()!=0){
                for (CountNumBo c: countNumBos) {
                    numList.put(c.getQdkbId()+"_"+c.getStatusTwo(),c.getNum());
                }
            }
        }
        for (WdqdBo w: list) {
            w.setAboutFaceNum(numList.get(w.getQdkbId()+"_2"));
            w.setToFaceNum(numList.get(w.getQdkbId()+"_3"));
            w.setOfferNum(numList.get(w.getQdkbId()+"_4"));
            w.setEntryNum(numList.get(w.getQdkbId()+"_6"));
        }

        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('system:wdqd:listuser')")
    @GetMapping(value = "/listuser/{qdkbId}")
    public TableDataInfo listuser(@PathVariable("qdkbId") Long qdkbId)
    {
//        startPage();
        List<WdqdBo>list = wdqdService.selectWdqdUserList(qdkbId);
        return getDataTable(list);
    }



    /**
     * 获取我的抢单/我的职位详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:wdqd:query')")
    @GetMapping(value = "/{orderId}")
    public AjaxResult getInfo(@PathVariable("orderId") Long orderId)
    {
        WdqdBo wdqdBo = wdqdService.selectWdqdByOrderId(orderId);
        YgVo ygVo=new YgVo();
        ygVo.setQdkbId(wdqdBo.getQdkbId());
        SysUser sysUser = getLoginUser().getUser();
        boolean contains9 = sysUser.getRoles().stream().anyMatch(v->v.getRoleId()==9L);
        boolean contains3OR4 = sysUser.getRoles().stream().anyMatch(v->v.getRoleId()==3L || v.getRoleId()==4L);
        boolean contains6 = sysUser.getRoles().stream().anyMatch(v->v.getRoleId()==6L);
        boolean contains1OR2=true;
        if(sysUser.getRoles()!=null && sysUser.getRoles().size()!=0){
            contains1OR2 = sysUser.getRoles().stream().anyMatch(v->v.getRoleId()==1L || v.getRoleId()==2L);
        }
        if(contains9){
            ygVo.setUserId(getUserId());
        }else if(contains3OR4){
            ygVo.setTlId(getUserId());
        }else if(contains6){
            ygVo.setPmId(getUserId());
        }else if(!contains1OR2){
            return AjaxResult.success();
        }
        Map<String,Integer> numList=new HashMap<>();
        List<CountNumBo> countNumBos = ygService.selectcountNumOne(ygVo);
        if(countNumBos!=null && countNumBos.size()!=0){
            for (CountNumBo c: countNumBos) {
                numList.put(c.getStatusTwo(),c.getNum());
            }
        }
        wdqdBo.setAboutFaceNum(numList.get("2"));
        wdqdBo.setToFaceNum(numList.get("3"));
        wdqdBo.setOfferNum(numList.get("4"));
        wdqdBo.setEntryNum(numList.get("6"));
        return success(wdqdBo);
    }

    /**
     * 新增我的抢单/我的职位
     */
    @PreAuthorize("@ss.hasPermi('system:wdqd:add')")
    @Log(title = "我的抢单/我的职位", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Wdqd wdqd)
    {
        SysUser sysUser = getLoginUser().getUser();
        boolean contains3OR4 = sysUser.getRoles().stream().anyMatch(v->v.getRoleId()==3L || v.getRoleId()==4L);
        if(!contains3OR4){
            throw new RuntimeException("除了TL其他成员角色暂不支持抢单");
        }
        wdqd.setUserId(getUserId());
        LambdaQueryWrapper<Wdqd> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(Wdqd::getOrderId);
        lambdaQueryWrapper.eq(Wdqd::getQdkbId,wdqd.getQdkbId());
        lambdaQueryWrapper.eq(Wdqd::getUserId,wdqd.getUserId());
        Wdqd dbWdqd = wdqdService.getOne(lambdaQueryWrapper);
        if(dbWdqd!=null){
            dbWdqd.setStatus("1");
            return toAjax(wdqdService.updateWdqd(dbWdqd));
        }
        LambdaQueryWrapper<Qdkb> lambdaQueryWrapper1=new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.select(Qdkb::getRecommendedOfficerCount,Qdkb::getQdkbId);
        lambdaQueryWrapper1.eq(Qdkb::getQdkbId,wdqd.getQdkbId());
        Qdkb qdkb = qdkbService.getOne(lambdaQueryWrapper1);
        qdkb.setRecommendedOfficerCount(qdkb.getRecommendedOfficerCount()+1);
        qdkbService.updateById(qdkb);
        wdqd.setCreateTime(DateUtils.getNowDate());

        return toAjax(wdqdService.insertWdqd(wdqd));
    }

    /**
     * 修改我的抢单/我的职位
     */
    @PreAuthorize("@ss.hasPermi('system:wdqd:edit')")
    @Log(title = "我的抢单/我的职位", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Wdqd wdqd)
    {
        return toAjax(wdqdService.updateWdqd(wdqd));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:wdqd:edit')")
    @Log(title = "请填写功能名称】", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus/{orderId}")
    public AjaxResult changeStatus(@PathVariable Long orderId)
    {

        return toAjax(wdqdService.updateWdqdStatus(orderId));
    }

    /**
     * 删除我的抢单/我的职位
     */
    @PreAuthorize("@ss.hasPermi('system:wdqd:remove')")
    @Log(title = "我的抢单/我的职位", businessType = BusinessType.DELETE)
    @DeleteMapping("/{orderIds}")
    public AjaxResult remove(@PathVariable Long[] orderIds)
    {
        return toAjax(wdqdService.deleteWdqdByOrderIds(orderIds));
    }
}
